using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class PlayerPrefsTool : EditorWindow
{
    private bool showConfirmation = true;
    private Vector2 scrollPosition;
    private Dictionary<string, string> allPreferences = new Dictionary<string, string>();

    [MenuItem("Tools/基础工具/本地缓存清理工具")]
    public static void ShowWindow()
    {
        GetWindow<PlayerPrefsTool>("缓存清理工具");
    }

    void OnGUI()
    {
        GUILayout.Label("PlayerPrefs 清理工具", EditorStyles.boldLabel);
        EditorGUILayout.Space();

        // 基本信息显示
        EditorGUILayout.BeginVertical(GUI.skin.box);
        GUILayout.Label($"当前游戏标识: {Application.productName}");
        GUILayout.Label($"公司名称: {Application.companyName}");
        GUILayout.Label($"版本: {Application.version}");
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();

        // 操作按钮
        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("扫描所有缓存", GUILayout.Height(30)))
        {
            ScanAllPreferences();
        }
        if (GUILayout.Button("刷新列表", GUILayout.Height(30)))
        {
            ScanAllPreferences();
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Space();

        // 危险操作区域
        EditorGUILayout.BeginVertical(GUI.skin.box);
        GUILayout.Label("危险操作区域", EditorStyles.boldLabel);

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("清除所有缓存", GUILayout.Height(25)))
        {
            ClearAllPreferences();
        }
        if (GUILayout.Button("清除选中项", GUILayout.Height(25)))
        {
            ClearSelectedPreferences();
        }
        EditorGUILayout.EndHorizontal();

        showConfirmation = EditorGUILayout.Toggle("显示确认对话框", showConfirmation);
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();

        // 缓存项列表
        GUILayout.Label($"找到 {allPreferences.Count} 个缓存项", EditorStyles.helpBox);

        if (allPreferences.Count > 0)
        {
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, GUILayout.Height(300));

            foreach (var pref in allPreferences)
            {
                EditorGUILayout.BeginHorizontal(GUI.skin.box);

                // 键名和值
                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField($"键: {pref.Key}", EditorStyles.boldLabel);
                EditorGUILayout.LabelField($"值: {pref.Value}");
                EditorGUILayout.EndVertical();

                // 操作按钮
                if (GUILayout.Button("删除", GUILayout.Width(60), GUILayout.Height(40)))
                {
                    DeleteSinglePreference(pref.Key);
                }

                EditorGUILayout.EndHorizontal();
                EditorGUILayout.Space();
            }

            EditorGUILayout.EndScrollView();
        }
        else
        {
            GUILayout.Label("没有找到缓存数据，点击\"扫描所有缓存\"按钮进行扫描", EditorStyles.helpBox);
        }

        // 快速操作区域
        EditorGUILayout.Space();
        GUILayout.Label("快速操作", EditorStyles.boldLabel);
        EditorGUILayout.BeginVertical(GUI.skin.box);

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("清除存档数据"))
        {
            ClearCommonSaveData();
        }
        if (GUILayout.Button("清除设置数据"))
        {
            ClearCommonSettings();
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("清除音频设置"))
        {
            ClearAudioSettings();
        }
        if (GUILayout.Button("清除图形设置"))
        {
            ClearGraphicsSettings();
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.EndVertical();
    }

    void ScanAllPreferences()
    {
        allPreferences.Clear();

#if UNITY_EDITOR_WIN
        // Windows 平台 - 从注册表读取
        ScanWindowsPreferences();
#elif UNITY_EDITOR_OSX
        // macOS 平台 - 从 plist 文件读取
        ScanMacPreferences();
#elif UNITY_EDITOR_LINUX
        // Linux 平台
        ScanLinuxPreferences();
#else
        // 其他平台使用通用方法
        ScanCommonPreferences();
#endif

        Debug.Log($"扫描完成！找到 {allPreferences.Count} 个 PlayerPrefs 项");
    }

    void ScanCommonPreferences()
    {
        // 这里尝试扫描一些常见的 PlayerPrefs 键
        string[] commonKeys = {
            "PlayerName", "Volume", "MusicVolume", "SFXVolume",
            "QualityLevel", "Resolution", "Fullscreen",
            "Coins", "Score", "Level", "Experience",
            "Settings_Music", "Settings_SFX", "Settings_Quality",
            "HighScore", "Progress", "Language", "Subtitles"
        };

        foreach (string key in commonKeys)
        {
            if (PlayerPrefs.HasKey(key))
            {
                string value = GetPlayerPrefValue(key);
                if (value != null)
                {
                    allPreferences[key] = value;
                }
            }
        }
    }

    // 修复的方法：安全地获取 PlayerPrefs 值
    string GetPlayerPrefValue(string key)
    {
        // 首先尝试获取字符串值
        if (PlayerPrefs.HasKey(key))
        {
            string stringValue = PlayerPrefs.GetString(key, null);
            if (!string.IsNullOrEmpty(stringValue))
            {
                return $"字符串: {stringValue}";
            }
        }

        // 然后尝试获取整数值
        if (PlayerPrefs.HasKey(key))
        {
            int intValue = PlayerPrefs.GetInt(key, int.MinValue);
            if (intValue != int.MinValue)
            {
                return $"整数: {intValue}";
            }
        }

        // 最后尝试获取浮点数值
        if (PlayerPrefs.HasKey(key))
        {
            float floatValue = PlayerPrefs.GetFloat(key, float.MinValue);
            if (floatValue != float.MinValue)
            {
                return $"浮点数: {floatValue}";
            }
        }

        return "未知类型";
    }

    void ScanWindowsPreferences()
    {
        try
        {
            // 由于 Unity 的限制，我们使用改进的通用扫描方法
            ScanCommonPreferences();

            // 添加一些 Windows 特定的常见键
            string[] windowsKeys = {
                "Screenmanager Resolution Width",
                "Screenmanager Resolution Height",
                "Screenmanager Is Fullscreen mode"
            };

            foreach (string key in windowsKeys)
            {
                if (PlayerPrefs.HasKey(key))
                {
                    string value = GetPlayerPrefValue(key);
                    if (value != null)
                    {
                        allPreferences[key] = value;
                    }
                }
            }
        }
        catch (System.Exception e)
        {
            Debug.LogWarning($"扫描 Windows 注册表失败: {e.Message}");
            ScanCommonPreferences();
        }
    }

    void ScanMacPreferences()
    {
        try
        {
            ScanCommonPreferences();
        }
        catch (System.Exception e)
        {
            Debug.LogWarning($"扫描 macOS plist 失败: {e.Message}");
            ScanCommonPreferences();
        }
    }

    void ScanLinuxPreferences()
    {
        try
        {
            ScanCommonPreferences();
        }
        catch (System.Exception e)
        {
            Debug.LogWarning($"扫描 Linux 配置失败: {e.Message}");
            ScanCommonPreferences();
        }
    }

    void ClearAllPreferences()
    {
        if (showConfirmation)
        {
            if (!EditorUtility.DisplayDialog("确认清除",
                $"确定要清除所有 {allPreferences.Count} 个缓存项吗？此操作不可撤销！",
                "清除所有", "取消"))
            {
                return;
            }
        }

        PlayerPrefs.DeleteAll();
        PlayerPrefs.Save();
        allPreferences.Clear();

        Debug.Log("所有 PlayerPrefs 数据已清除！");
        EditorUtility.DisplayDialog("完成", "所有缓存数据已成功清除！", "确定");
    }

    void ClearSelectedPreferences()
    {
        if (allPreferences.Count == 0)
        {
            EditorUtility.DisplayDialog("提示", "没有可清除的缓存项", "确定");
            return;
        }

        if (showConfirmation)
        {
            if (!EditorUtility.DisplayDialog("确认清除",
                "确定要清除所有扫描到的缓存项吗？",
                "清除", "取消"))
            {
                return;
            }
        }

        foreach (string key in allPreferences.Keys)
        {
            PlayerPrefs.DeleteKey(key);
        }
        PlayerPrefs.Save();

        int clearedCount = allPreferences.Count;
        allPreferences.Clear();

        Debug.Log($"清除了 {clearedCount} 个缓存项");
        EditorUtility.DisplayDialog("完成", $"成功清除 {clearedCount} 个缓存项！", "确定");
    }

    void DeleteSinglePreference(string key)
    {
        if (showConfirmation)
        {
            if (!EditorUtility.DisplayDialog("确认删除",
                $"确定要删除键 '{key}' 吗？",
                "删除", "取消"))
            {
                return;
            }
        }

        PlayerPrefs.DeleteKey(key);
        PlayerPrefs.Save();
        allPreferences.Remove(key);

        Debug.Log($"已删除缓存项: {key}");
    }

    void ClearCommonSaveData()
    {
        string[] saveKeys = {
            "PlayerName", "Coins", "Score", "Level", "Experience",
            "HighScore", "Progress", "Inventory", "Achievements",
            "CurrentLevel", "TotalPlayTime", "UnlockedLevels"
        };

        int deletedCount = 0;
        foreach (string key in saveKeys)
        {
            if (PlayerPrefs.HasKey(key))
            {
                PlayerPrefs.DeleteKey(key);
                deletedCount++;
            }
        }
        PlayerPrefs.Save();

        Debug.Log($"清除了 {deletedCount} 个存档数据项");
        EditorUtility.DisplayDialog("完成", $"已清除 {deletedCount} 个存档数据项", "确定");

        ScanAllPreferences();
    }

    void ClearCommonSettings()
    {
        string[] settingKeys = {
            "Volume", "MusicVolume", "SFXVolume", "Language",
            "Subtitles", "Controls", "Vibration", "Notifications"
        };

        int deletedCount = 0;
        foreach (string key in settingKeys)
        {
            if (PlayerPrefs.HasKey(key))
            {
                PlayerPrefs.DeleteKey(key);
                deletedCount++;
            }
        }
        PlayerPrefs.Save();

        Debug.Log($"清除了 {deletedCount} 个设置项");
        EditorUtility.DisplayDialog("完成", $"已清除 {deletedCount} 个设置项", "确定");

        ScanAllPreferences();
    }

    void ClearAudioSettings()
    {
        string[] audioKeys = {
            "MasterVolume", "MusicVolume", "SFXVolume", "VoiceVolume",
            "AudioEnabled", "Mute", "OutputDevice"
        };

        int deletedCount = 0;
        foreach (string key in audioKeys)
        {
            if (PlayerPrefs.HasKey(key))
            {
                PlayerPrefs.DeleteKey(key);
                deletedCount++;
            }
        }
        PlayerPrefs.Save();

        Debug.Log($"清除了 {deletedCount} 个音频设置项");
        EditorUtility.DisplayDialog("完成", $"已清除 {deletedCount} 个音频设置项", "确定");

        ScanAllPreferences();
    }

    void ClearGraphicsSettings()
    {
        string[] graphicsKeys = {
            "QualityLevel", "Resolution", "Fullscreen",
            "VSync", "AntiAliasing", "ShadowQuality",
            "TextureQuality", "AnisotropicFiltering"
        };

        int deletedCount = 0;
        foreach (string key in graphicsKeys)
        {
            if (PlayerPrefs.HasKey(key))
            {
                PlayerPrefs.DeleteKey(key);
                deletedCount++;
            }
        }
        PlayerPrefs.Save();

        Debug.Log($"清除了 {deletedCount} 个图形设置项");
        EditorUtility.DisplayDialog("完成", $"已清除 {deletedCount} 个图形设置项", "确定");

        ScanAllPreferences();
    }

    // [MenuItem("Tools/基础工具/快速清除所有缓存 (无确认)")]
    // static void QuickClearAll()
    // {
    //     PlayerPrefs.DeleteAll();
    //     PlayerPrefs.Save();
    //     Debug.Log("快速清除：所有 PlayerPrefs 数据已删除！");
    // }

    // [MenuItem("Tools/快速清除存档数据")]
    // static void QuickClearSaveData()
    // {
    //     PlayerPrefsTool window = GetWindow<PlayerPrefsTool>();
    //     window.ClearCommonSaveData();
    // }
}